#pragma once
#include <iostream>
#include <cstdio>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <fcntl.h>
#include <unistd.h>
using namespace std;

#include "Comm.hpp"

#define PATH "."
#define FILENAME "fifo"

//#define FIFO_FILE "fifo"

class NamedFifo
{
public:
    NamedFifo(const string& path,const string& name)
        :_path(path),_name(name)
    {
        _fifoname =_path + "/" + _name;
        umask(0);
        //创建管道
        int n = mkfifo(_fifoname.c_str(), 0666);
        if(n < 0)
        {
            cout << "mkdir fifo error" << endl;
            ERR_EXIT("makefifo");
        }
        else
        {
            cout << "fifo success" << endl;
        }
    }

    ~NamedFifo()
    {
        //删除管道文件
        int n = unlink(_fifoname.c_str());
        if(n == 0)
        {
            cout << "unlink fifo" << endl;
        }
        else
        {
            // perror("remove fifo fail");
            // exit(1);

            ERR_EXIT("unlink");
        }
    }
private:
    string _path;
    string _name;
    string _fifoname;
};

class FileOper
{
public:
    FileOper(const string& path,const string& name)
        :_path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }

    ~FileOper()
    {

    }
    
    void OpenForRead()
    {
        // 打开, write 方没有执行open的时候，read方，就要在open内部进行阻塞
        // 直到管道文件打开了，open才会返回！
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open");
        }
        cout << "open fifo success" << endl;
    }

    void OpenForWrite()
    {
        //写
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if(_fd < 0)
        {
            ERR_EXIT("open");
        }
        cout << "open fifo success" << endl;
    }

    void Wakeup()
    {
        //写操作
        char c = ' ';
        int n = write(_fd, &c, 1);
        printf("尝试唤醒: %d\n", n);
    }

    bool Wait()
    {
        //读操作
        char c;
        int n = read(_fd, &c, 1);
        if(n > 0)
        {
            printf("唤醒成功: %d\n", n);
            return true;
        }
        else
        {
            return false;
        }
    }

    void Close()
    {
        if(_fd > 0)
        {
            close(_fd);
        }
    }

private:
    string _path;
    string _name;
    string _fifoname;
    int _fd;
};